package client.routeForm;
import client.ClientSender;
import exception.RouteNotFoundException;
import exception.InvalidArgumentsException;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.concurrent.TimeoutException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.Route;
/**
 *основная панель для маршрутов
 * @author GeneraL
 */
public class RouteShowPanel extends javax.swing.JPanel {

    /**
     * Creates new form RouteShowPanel
     */
    private ArrayList<Integer> routeId;
    private ArrayList<String> routeType;
    private ArrayList<Double> routeDist;
    private ArrayList<Integer> routeAId;
    private ArrayList<Integer> routeBId;
    
    public RouteShowPanel() {
        initComponents();
    }
    /**
     * перезагрузка маршрутов из БД
     */
    public void reloadRoutes(){
     try{
     ClientSender sender=new ClientSender();
     ArrayList<Route> routes=sender.sendRoute("routelist");
     sender.close();
     ArrayList<Integer> routeId=new ArrayList<Integer>();
     ArrayList<String> routeType=new ArrayList<String>();
     ArrayList<Double> routeDist=new ArrayList<Double> ();
     ArrayList<Integer> routeAId=new ArrayList<Integer>();
     ArrayList<Integer> routeBId=new ArrayList<Integer>();
     for(int i=0;i<routes.size();i++){
         routeId.add(routes.get(i).getId());
         routeType.add(routes.get(i).getClass().getSimpleName());
         routeDist.add(routes.get(i).getDistance());
         routeAId.add(routes.get(i).getTakeOffPort());
         routeBId.add(routes.get(i).getLandingPort());
         
     }
     this.setData(routeId,routeType, routeDist, routeAId,routeBId);
        }catch (UnknownHostException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
            System.exit(0);
        }
        catch (IOException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
            System.exit(0);
        }
        catch (TimeoutException | RouteNotFoundException | InvalidArgumentsException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
        }
    }

/**
 * метод для установки значений
 * @param routeId
 * @param routeType
 * @param routeDist
 * @param routeAId идентификатор пункта А
 * @param routeBId идентификатор пункта В
 */
    public void setData(ArrayList<Integer> routeId,
     ArrayList<String> routeType,
     ArrayList<Double> routeDist,
     ArrayList<Integer> routeAId,
     ArrayList<Integer> routeBId){
       this.routeId=routeId;
        this.routeType=routeType;
       this.routeDist=routeDist;
       this.routeAId=routeAId;
       this.routeBId=routeBId;
       
       String[] routeUniqueName=new String[routeType.size()];
       javax.swing.DefaultListModel model=new javax.swing.DefaultListModel<>();
       for(int i=0;i<routeType.size();i++){
           routeUniqueName[i]=new String("№"+routeId.get(i));
           model.addElement(routeUniqueName[i]);
       }
      
        this.routeList.setModel(model);
        this.delButton.setEnabled(false);
        this.setButton.setEnabled(false);
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        addButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        routeList = new javax.swing.JList();
        jPanel2 = new javax.swing.JPanel();
        routeInfoPanel1 = new client.routeForm.RouteInfoPanel();
        setButton = new javax.swing.JButton();
        delButton = new javax.swing.JButton();

        jSplitPane1.setDividerLocation(150);

        addButton.setText("Добавить маршрут");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        routeList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        routeList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                routeListMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(routeList);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(addButton, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
            .addComponent(jScrollPane1)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(addButton))
        );

        jSplitPane1.setLeftComponent(jPanel1);

        setButton.setText("Сохранить изменения");
        setButton.setEnabled(false);
        setButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                setButtonActionPerformed(evt);
            }
        });

        delButton.setText("Удалить маршрут");
        delButton.setEnabled(false);
        delButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                delButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(routeInfoPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(setButton, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
                    .addComponent(delButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(48, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(routeInfoPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(setButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(delButton)
                .addGap(0, 52, Short.MAX_VALUE))
        );

        jSplitPane1.setRightComponent(jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1)
        );
    }// </editor-fold>//GEN-END:initComponents
/**
 * добавление данных
 * @param evt 
 */
    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
        // TODO add your handling code here:
         AddRouteDialog dialog = new AddRouteDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                    }
                });
            Route route=dialog.showDialog();
        this.reloadRoutes();//заглушка! перезагрузка всей базы данных маршрутов
    }//GEN-LAST:event_addButtonActionPerformed
/**
 * вывод детализации о маршруте
 * @param evt 
 */
    private void routeListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_routeListMouseClicked
        // TODO add your handling code here:
        int i=this.routeList.getSelectedIndex();
        int aId=this.routeAId.get(i);
        int bId=this.routeBId.get(i);
        this.routeInfoPanel1.reloadPorts();
        this.routeInfoPanel1.setData(routeType.get(i),this.routeDist.get(i) ,
                this.routeAId.get(i),this.routeBId.get(i));
        
        this.delButton.setEnabled(true);
        this.setButton.setEnabled(true);

    }//GEN-LAST:event_routeListMouseClicked
/**
 * переименовать поля маршрута
 * @param evt 
 */
    private void setButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_setButtonActionPerformed
        // TODO add your handling code here:
      try{
        read:{
          try{
          int i=this.routeList.getSelectedIndex();
        ClientSender send=new ClientSender();
        send.sendRoute("setroute "+routeId.get(i)+" "+routeInfoPanel1.getAId()+
                " "+routeInfoPanel1.getBId()+" "+routeInfoPanel1.getDistance());
        this.reloadRoutes();
          }catch(java.lang.NumberFormatException e){
              JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
                 break read;
        }
        }
        }catch (UnknownHostException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
        }
        catch (IOException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
        }
        catch (TimeoutException | RouteNotFoundException | InvalidArgumentsException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
        }

    }//GEN-LAST:event_setButtonActionPerformed
/**
 * удаление маршрута
 * @param evt 
 */
    private void delButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delButtonActionPerformed
        // TODO add your handling code here:
       try{
          int i=this.routeList.getSelectedIndex();
        ClientSender send=new ClientSender();
        send.sendRoute("delroute "+routeId.get(i));
        this.reloadRoutes();
        }catch (UnknownHostException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
        }
        catch (IOException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
        }
        catch (TimeoutException | RouteNotFoundException | InvalidArgumentsException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
        }
    }//GEN-LAST:event_delButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JButton delButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private client.routeForm.RouteInfoPanel routeInfoPanel1;
    private javax.swing.JList routeList;
    private javax.swing.JButton setButton;
    // End of variables declaration//GEN-END:variables
}
